package com.banciyuan.bcywebview.biz.event;

import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.textview.ExpandedTextView;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.regex.MatchFilterImpl;
import com.banciyuan.bcywebview.utils.regex.MyLinkfy;
import com.banciyuan.bcywebview.utils.regex.MyRegex;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.string.UnderLineUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.util.List;

import de.greenrobot.daoexample.model.Card;
import de.greenrobot.daoexample.model.Event;
import de.greenrobot.daoexample.model.TagDetail;


public class EventDetailAdapter extends RecyclerView.Adapter {
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private List<Card> mCardList;
    private String mType;
    private Event mEvent;

    public static final int HEADER_TYPE = 0;
    public static final int MAIN_TYPE = 1;
    public static final int WRITE_TYPE = 2;
    public static final int DAILY_TYPE = 3;
    public static final int LONG_DAILY_TYPE = 4;
    public static final int VIDEO_TYPE = 5;

    private EventHeaderViewHolder eventHeaderViewHolder;

    public EventDetailAdapter(Context context, List<Card> cardList) {
        mContext = context;
        mCardList = cardList;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setType(String type) {
        mType = type;
    }

    public void setEvent(Event event) {
        mEvent = event;
        setHeaderUi();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0)
            return HEADER_TYPE;
        String type = mCardList.get(position - 1).getType();
        if ("coser".equals(mType) || "drawer".equals(mType)) {
            return MAIN_TYPE;
        } else if ("writer".equals(mType)) {
            return WRITE_TYPE;
        } else if ("daily".equals(mType)) {
            if ("larticle".equals(type))
                return LONG_DAILY_TYPE;
            if ("svideo".equals(type))
                return VIDEO_TYPE;
            return DAILY_TYPE;
        }
        return MAIN_TYPE;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case HEADER_TYPE:
                eventHeaderViewHolder = new EventHeaderViewHolder(mLayoutInflater.inflate(R.layout.event_detail_header, parent, false));
                setHeaderUi();
                return eventHeaderViewHolder;
            case MAIN_TYPE:
            default:
                return new MainViewHolder(mLayoutInflater.inflate(R.layout.event_detail_item_main, parent, false));
            case WRITE_TYPE:
                return new NovelViewHolder(mLayoutInflater.inflate(R.layout.event_detail_item_novel, parent, false));
            case DAILY_TYPE:
                return new DailyViewHolder(mLayoutInflater.inflate(R.layout.event_detail_item_daily, parent, false));
            case LONG_DAILY_TYPE:
                return new LongDailyViewHolder(mLayoutInflater.inflate(R.layout.event_detail_item_longdaily, parent, false));
            case VIDEO_TYPE:
                return new VideoViewHolder(mLayoutInflater.inflate(R.layout.event_detail_item_video, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case HEADER_TYPE:
                break;
            case MAIN_TYPE:
                setMainUi((MainViewHolder) holder, mCardList.get(position - 1));
                break;
            case WRITE_TYPE:
                setWriteUi((NovelViewHolder) holder, mCardList.get(position - 1));
                break;
            case DAILY_TYPE:
                setDailyUi((DailyViewHolder) holder, mCardList.get(position - 1));
                break;
            case LONG_DAILY_TYPE:
                setLongDailyUi((LongDailyViewHolder) holder, mCardList.get(position - 1));
                break;
            case VIDEO_TYPE:
                setVideoUI((VideoViewHolder) holder, mCardList.get(position - 1));
                break;
            default:
                break;
        }
    }

    private SpannableString processIntroFunction(String text) {
        SpannableString spannableString = new SpannableString(text);
        MyLinkfy.addLinks(spannableString, MyRegex.plist.get(0), "bcyapp_", new MatchFilterImpl(), null);
        UnderLineUtil.DisUnderLine(mContext, spannableString);
        return spannableString;
    }

    private void setHeaderUi() {
        if (null == mEvent || null == eventHeaderViewHolder)
            return;
        ImageLoader.getInstance().displayImage(mEvent.getCover(), eventHeaderViewHolder.ivEventCover, ImageOptions.options);
        if (!TextUtils.isEmpty(mEvent.getTitle())) {
            eventHeaderViewHolder.tvEventTitle.setText(mEvent.getTitle());
        }
        if (!TextUtils.isEmpty(mEvent.getTag_name())) {
            eventHeaderViewHolder.tvEventActivity.setText(mEvent.getTag_name());
        }
        if (!TextUtils.isEmpty(mEvent.getTag_name())) {
            eventHeaderViewHolder.tvEventType.setText(mEvent.getType_name());
        }
        eventHeaderViewHolder.tvEventLandMark.setMaxLines(2);
        if (!TextUtils.isEmpty(mEvent.getIntro())) {
            ((View) (eventHeaderViewHolder.tvEventLandMark.getParent())).setVisibility(View.VISIBLE);
            eventHeaderViewHolder.tvEventLandMark.setText(processIntroFunction(StringUtil.htmlDecoder(mEvent.getIntro())), true, new ExpandedTextView.OnProcessClick() {
                @Override
                public SpannableString onProcessSucc(CharSequence text) {
                    return processIntroFunction(text.toString());
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    eventHeaderViewHolder.tvEventLandMark.setMaxLines(200);
                    eventHeaderViewHolder.tvEventLandMark.requestLayout();
                }
            }, R.string.open_event_no_format, 2);
        } else {
            eventHeaderViewHolder.tvEventLandMark.setVisibility(View.GONE);
        }
        eventHeaderViewHolder.tvEventTimer.setText(String.format(mContext.getString(R.string.event_status_format),
                StringUtil.getEventTime(mEvent.getStime()), StringUtil.getEventTime(mEvent.getEtime()), mEvent.getEvent_status()));
        if (mEvent.isEvent_end()) {
            eventHeaderViewHolder.tvEventJoin.setText(mEvent.getEvent_status());
            eventHeaderViewHolder.tvEventJoin.setBackgroundResource(R.drawable.update_grey_btn);
        } else {
            eventHeaderViewHolder.tvEventJoin.setText(mContext.getString(R.string.i_want_join));
            eventHeaderViewHolder.tvEventJoin.setBackgroundResource(R.drawable.update_red_btn);
            eventHeaderViewHolder.tvEventJoin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((EventDetailActivity) mContext).goPost();
                }
            });
        }
        eventHeaderViewHolder.viewSortByHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setHotIndicator();
                ((EventDetailActivity) mContext).setHotIndicator();
            }
        });
        eventHeaderViewHolder.viewSortByUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUpdateIndicator();
                ((EventDetailActivity) mContext).setUpdateIndicator();
            }
        });
    }

    public void setUpdateIndicator() {
        if (null != eventHeaderViewHolder) {
            eventHeaderViewHolder.hotIndicator.setVisibility(View.GONE);
            eventHeaderViewHolder.updateIndicator.setVisibility(View.VISIBLE);
            eventHeaderViewHolder.viewUpdateTimeTips.setVisibility(View.GONE);
        }
    }

    public void setHotIndicator() {
        if (null != eventHeaderViewHolder) {
            eventHeaderViewHolder.hotIndicator.setVisibility(View.VISIBLE);
            eventHeaderViewHolder.updateIndicator.setVisibility(View.GONE);
            eventHeaderViewHolder.viewUpdateTimeTips.setVisibility(View.VISIBLE);
        }
    }

    private void setVideoUI(VideoViewHolder holder, Card card) {
        ImageLoader.getInstance().displayImage(card.getCover(), holder.ivVideoCover, ImageOptions.options);
        setCardBottomData(holder, card);
        OnClick onClick = new OnClick(card);
        holder.tvUname.setOnClickListener(onClick);
        holder.ivVideoCover.setOnClickListener(onClick);
    }

    private void setLongDailyUi(LongDailyViewHolder holder, Card card) {
        if (!TextUtils.isEmpty(card.getTitle()))
            holder.tvLongDailyTitle.setText(card.getTitle());
        if (!TextUtils.isEmpty(card.getCover())) {
            ImageLoader.getInstance().displayImage(card.getCover(), holder.ivLongDailyCover, ImageOptions.options);
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                holder.ivLongDailyCover.setImageDrawable(mContext.getResources().getDrawable(R.drawable.larticle_cover, mContext.getTheme()));
            } else {
                holder.ivLongDailyCover.setImageDrawable(mContext.getResources().getDrawable(R.drawable.larticle_cover));
            }
        }
        setCardBottomData(holder, card);
        OnClick onClick = new OnClick(card);
        holder.tvUname.setOnClickListener(onClick);
        holder.ivLongDailyCover.setOnClickListener(onClick);
    }

    private void setDailyUi(DailyViewHolder holder, Card card) {
        if (!TextUtils.isEmpty(card.getImg_src())) {
            holder.ivDailyCover.setVisibility(View.VISIBLE);
            holder.tvDailyText.setVisibility(View.GONE);
            holder.dailyNopicIcon.setVisibility(View.GONE);
            holder.viewDaily.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            ImageLoader.getInstance().displayImage(card.getImg_src(), holder.ivDailyCover, ImageOptions.options);
        } else {
            holder.ivDailyCover.setVisibility(View.INVISIBLE);
            holder.tvDailyText.setVisibility(View.VISIBLE);
            holder.dailyNopicIcon.setVisibility(View.VISIBLE);
            holder.viewDaily.setBackgroundColor(mContext.getResources().getColor(R.color.small_card_bg));
            if (!TextUtils.isEmpty(card.getPlain())) {
                holder.tvDailyText.setText(Html.fromHtml(card.getPlain()));
            }
        }
        setCardBottomData(holder, card);
        OnClick onClick = new OnClick(card);
        holder.tvUname.setOnClickListener(onClick);
        holder.viewDaily.setOnClickListener(onClick);
    }

    private void setWriteUi(NovelViewHolder holder, Card card) {
        ImageLoader.getInstance().displayImage(card.getCover(), holder.ivNoverCover, ImageOptions.options);
        if (!TextUtils.isEmpty(card.getTitle())) {
            holder.tvNovelTitle.setText(Html.fromHtml(card.getTitle()));
        }
        holder.tvNovelTag.setText(getTagString(card));
        setCardBottomData(holder, card);
        OnClick onClick = new OnClick(card);
        holder.tvUname.setOnClickListener(onClick);
        holder.ivNoverCover.setOnClickListener(onClick);
    }

    private String getTagString(Card mItem) {
        StringBuffer sb = new StringBuffer();
        if (null != mItem && null != mItem.getPost_tags()) {
            for (TagDetail s : mItem.getPost_tags()) {
                sb.append(s.getTag_name());
                sb.append("/");
            }
            if (sb.length() > 0)
                sb.delete(sb.length() - 1, sb.length());
        }
        return sb.toString();
    }

    private void setMainUi(MainViewHolder holder, Card card) {
        ImageLoader.getInstance().displayImage(card.getImg_src(), holder.ivMainCover, ImageOptions.options);
        setCardBottomData(holder, card);
        OnClick onClick = new OnClick(card);
        holder.tvUname.setOnClickListener(onClick);
        holder.ivMainCover.setOnClickListener(onClick);
    }

    private void setCardBottomData(EventBottomViewHolder holder, Card card) {
        if (!TextUtils.isEmpty(card.getUname())) {
            holder.tvUname.setText(card.getUname());
        }
        if (card.isDingStart()) {
            holder.tvZanNum.setVisibility(View.VISIBLE);
            holder.tvZanNum.setText(String.format(mContext.getString(R.string.event_zan_format), card.getDing_num()));
        } else {
            holder.tvZanNum.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return mCardList.size() + 1;
    }

    private class MainViewHolder extends EventBottomViewHolder {
        ImageView ivMainCover;

        public MainViewHolder(View itemView) {
            super(itemView);
            ivMainCover = (ImageView) itemView.findViewById(R.id.iv_event_cover);
        }
    }

    private class NovelViewHolder extends EventBottomViewHolder {
        ImageView ivNoverCover;
        TextView tvNovelTitle;
        TextView tvNovelTag;

        public NovelViewHolder(View itemView) {
            super(itemView);
            ivNoverCover = (ImageView) itemView.findViewById(R.id.siv_item_novel);
            tvNovelTitle = (TextView) itemView.findViewById(R.id.tv_write_title);
            tvNovelTag = (TextView) itemView.findViewById(R.id.tv_write_tag);
        }
    }

    private class DailyViewHolder extends EventBottomViewHolder {
        ImageView ivDailyCover;
        TextView tvDailyText;
        View dailyNopicIcon;
        View viewDaily;

        public DailyViewHolder(View itemView) {
            super(itemView);
            ivDailyCover = (ImageView) itemView.findViewById(R.id.siv_daily_item);
            tvDailyText = (TextView) itemView.findViewById(R.id.daily_text);
            dailyNopicIcon = itemView.findViewById(R.id.iv_daily_nopic_icon);
            viewDaily = itemView.findViewById(R.id.view_daily_item);
        }
    }

    private class LongDailyViewHolder extends EventBottomViewHolder {
        ImageView ivLongDailyCover;
        TextView tvLongDailyTitle;

        public LongDailyViewHolder(View itemView) {
            super(itemView);
            ivLongDailyCover = (ImageView) itemView.findViewById(R.id.siv_item_longdaily);
            tvLongDailyTitle = (TextView) itemView.findViewById(R.id.tv_longdaily_title);
        }
    }

    private class VideoViewHolder extends EventBottomViewHolder {
        ImageView ivVideoCover;

        public VideoViewHolder(View itemView) {
            super(itemView);
            ivVideoCover = (ImageView) itemView.findViewById(R.id.siv_item_video);
        }
    }

    private class EventBottomViewHolder extends RecyclerView.ViewHolder {
        TextView tvUname;
        TextView tvZanNum;

        public EventBottomViewHolder(View itemView) {
            super(itemView);
            tvUname = (TextView) itemView.findViewById(R.id.tv_uname);
            tvZanNum = (TextView) itemView.findViewById(R.id.tv_zan_count);
        }
    }

    private class EventHeaderViewHolder extends RecyclerView.ViewHolder {
        ImageView ivEventCover;
        TextView tvEventType;
        TextView tvEventTitle;
        TextView tvEventTimer;
        TextView tvEventActivity;
        ExpandedTextView tvEventLandMark;
        TextView tvEventJoin;
        View viewSortByHot;
        View viewSortByUpdate;
        View hotIndicator;
        View updateIndicator;
        View viewUpdateTimeTips;

        public EventHeaderViewHolder(View itemView) {
            super(itemView);
            ivEventCover = (ImageView) itemView.findViewById(R.id.iv_event_cover);
            tvEventType = (TextView) itemView.findViewById(R.id.tv_event_type);
            tvEventTitle = (TextView) itemView.findViewById(R.id.tv_event_title);
            tvEventTimer = (TextView) itemView.findViewById(R.id.tv_event_timer);
            tvEventActivity = (TextView) itemView.findViewById(R.id.tv_event_activity);
            tvEventLandMark = (ExpandedTextView) itemView.findViewById(R.id.tv_event_landmark);
            tvEventJoin = (TextView) itemView.findViewById(R.id.tv_event_join);
            viewSortByHot = itemView.findViewById(R.id.view_sort_by_hot);
            viewSortByUpdate = itemView.findViewById(R.id.view_sort_by_update);
            hotIndicator = itemView.findViewById(R.id.hot_indicator);
            updateIndicator = itemView.findViewById(R.id.update_indicator);
            viewUpdateTimeTips = itemView.findViewById(R.id.tv_update_tiem_tips);
        }
    }

    class OnClick implements View.OnClickListener {
        Card mItem;

        public OnClick(Card item) {
            mItem = item;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_event_cover:
                    switch (mType) {
                        case "coser":
                            DetailDataHelper.gotoCosDetail(mContext, mItem.getRp_id(), mItem.getCp_id(), false);
                            break;
                        case "drawer":
                            DetailDataHelper.gotoDrawerDetail(mContext, mItem.getRp_id(), mItem.getDp_id(), false);
                            break;
                    }
                    break;
                case R.id.siv_item_novel:
                    DetailDataHelper.gotoWriterDetail(mContext, mItem.getRp_id(), mItem.getWp_id(), false);
                    break;
                case R.id.view_daily_item:
                case R.id.siv_item_video:
                case R.id.siv_item_longdaily:
                    DetailDataHelper.gotoDailyDetail(mContext, mItem.getUd_id(), false);
                    break;
                case R.id.tv_uname:
                    gotoUtil.gotoAct(mContext, SmoothPersonActivity.class, mItem.getUid());
                    break;
            }
        }
    }

}
